package com.developer.platform.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.developer.platform.domain.QuartzJob;
import com.developer.platform.domain.scheduler.QuartzScheduler;
import com.developer.platform.domain.service.IQuartzJobService;
import com.developer.platform.infrastructure.data.mapper.QuartzJobMapper;
import com.developer.platform.infrastructure.enums.StatusEnum;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2021-01-07
 */
@Service
public class QuartzJobServiceImpl implements IQuartzJobService {

  private final QuartzJobMapper quartzJobMapper;
  private final QuartzScheduler quartzScheduler;

  public QuartzJobServiceImpl(
      QuartzJobMapper quartzJobMapper,
      QuartzScheduler quartzScheduler) {
    this.quartzJobMapper = quartzJobMapper;
    this.quartzScheduler = quartzScheduler;
  }

  @Override
  public void save(QuartzJob quartzJob) {
    this.delete(quartzJob);
    if(StatusEnum.Y.equals(quartzJob.getStatus())){
      quartzJob.setStatus(StatusEnum.N);
      quartzJobMapper.insert(quartzJob);
      quartzScheduler.addJob(quartzJob);
    }
  }

  @Override
  public void update(QuartzJob quartzJob) {

  }

  @Override
  public void delete(QuartzJob quartzJob) {
    LambdaQueryWrapper<QuartzJob> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(QuartzJob::getName, quartzJob.getName());
    queryWrapper.eq(QuartzJob::getSubgroup, quartzJob.getSubgroup());
    queryWrapper.eq(QuartzJob::getCore, quartzJob.getCore());
    queryWrapper.eq(QuartzJob::getJobData, quartzJob.getJobData());
    quartzJobMapper.delete(queryWrapper);
    quartzScheduler.deleteJob(quartzJob.getName(), quartzJob.getSubgroup());
  }

  @Override
  public void close(String name, String subgroup) {
    LambdaQueryWrapper<QuartzJob> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(QuartzJob::getName, name);
    queryWrapper.eq(QuartzJob::getSubgroup, subgroup);
    queryWrapper.eq(QuartzJob::getStatus, StatusEnum.N);
    quartzJobMapper.update(new QuartzJob(StatusEnum.Y), queryWrapper);
    quartzScheduler.deleteJob(name, subgroup);
  }

}
